package com.dayatang.android.Activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class LocationMe extends Activity {
	/**
	 * mTxtLocal显示结果 mLocalOkListener接口对象的引用 mProgressDialog进度条
	 * HttpClient，HttpParams timeout超时设置
	 */
	private TextView mTxtLocal = null;
	private OnGetLocalOkListener mLocalOkListener = null;
	private ProgressDialog mProgressDialog = null;
	private HttpClient httpclient;
	private HttpParams httpParameters;
	private int timeoutConnection = 3000;
	private int timeoutSocket = 5000;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 布局
		RelativeLayout mRlayout = new RelativeLayout(this);
		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
		Button mBtnGetLocal = new Button(this);
		mBtnGetLocal.setText("Get Me-Location.");
		mRlayout.addView(mBtnGetLocal, params);
		mBtnGetLocal.setId(11);
		// 设置onClickListener监听事件
		mBtnGetLocal.setOnClickListener(mOnClickListener);
		params = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.BELOW, 11);
		mTxtLocal = new TextView(this);
		mRlayout.addView(mTxtLocal, params);
		setContentView(mRlayout);
	}

	// 监听对象，这里是个匿名内部类.
	private OnClickListener mOnClickListener = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			getItude();
		}// end onClick;
	};

	// 通过经纬度获取地理信息
	private void getLocalByItude(String latitude, String longitude) {
		HttpURLConnection conn = null;
		String line = null;
		try {

			URL url = new URL("http://maps.google.cn/maps/geo?key=abcdefg&q="
					+ latitude + "," + longitude);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(timeoutConnection);
			conn.setReadTimeout(timeoutSocket);
			conn.setRequestMethod("GET");
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufReader = new BufferedReader(inStreamReader);
			StringBuffer bufStr = new StringBuffer();

			while ((line = bufReader.readLine()) != null) {
				bufStr.append(line);
			}
			line = bufStr.toString();
			if (line != null && line.length() > 0) {
				JSONObject jsonobject = new JSONObject(line);
				JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")
						.toString());
				line = "";
				for (int i = 0; i < jsonArray.length(); i++) {
					line = jsonArray.getJSONObject(i).getString("address");
				}
				// 回调
				mLocalOkListener.onGetOk(line);

			}
		} catch (Exception e) {
			// TODO: handle exception
			mLocalOkListener.onGetOk("");
		} finally {
			if (conn != null) {
				conn.disconnect();
				mLocalOkListener.onGetOk(line);
			}
		}
	}

	// 获得主线程的Handler
	private Handler mHandler = new Handler(Looper.getMainLooper());

	private void getItude() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("正在获取中...");
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.show();
		// 匿名内部类,回调调用的函数
		this.setOnGetLocalOkListener(new OnGetLocalOkListener() {
			public void onGetOk(String local) {
				// TODO Auto-generated method stub
				final String mlocal = local;
				mHandler.post(new Runnable() {

					public void run() {
						// TODO Auto-generated method stub
						if (mlocal.length() > 0) {
							mTxtLocal.setText(mlocal);
							System.out.println("onGetOk........");
							new Thread(new Runnable() {

								public void run() {
									// TODO Auto-generated method stub
									//saveLocal(mlocal);
									Log.i("123", mlocal);
								}
							}).start();
							mProgressDialog.dismiss();

						} else {
							mTxtLocal.setText("获取位置失败,请检查网络是否开启");
							mProgressDialog.dismiss();
						}

					}
				});

			}
		});
		// 开启新的线程去获取经纬度
		new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
				String operator = mTelNet.getNetworkOperator();
				String mcc = operator.substring(0, 3);
				String mnc = operator.substring(3);
				GsmCellLocation location = (GsmCellLocation) mTelNet
						.getCellLocation();
				int cid = location.getCid();
				int lac = location.getLac();
				Log.i("123", String.valueOf(cid) +"++"+ String.valueOf(lac));
				httpParameters = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpConnectionParams
						.setSoTimeout(httpParameters, timeoutSocket);
				httpclient = new DefaultHttpClient(httpParameters);
				HttpPost post = new HttpPost("http://www.google.com/loc/json");
				try {
					JSONObject holder = new JSONObject();
					holder.put("version", "1.1.0");
					holder.put("host", "maps.google.com");
					holder.put("address_language", "zh_CN");
					holder.put("request_address", true);

					JSONObject tower = new JSONObject();
					tower.put("mobile_country_code", mcc);
					tower.put("mobile_network_code", mnc);
					tower.put("cell_id", cid);
					tower.put("location_area_code", lac);

					JSONArray towerarray = new JSONArray();
					towerarray.put(tower);

					holder.put("cell_towers", towerarray);

					StringEntity query = new StringEntity(holder.toString());
					Log.i("123", holder.toString());
					post.setEntity(query);
					HttpResponse response = httpclient.execute(post);
					HttpEntity entity = response.getEntity();
					BufferedReader buffReader = new BufferedReader(
							new InputStreamReader(entity.getContent()));
					StringBuffer strBuff = new StringBuffer();
					String result = null;
					while ((result = buffReader.readLine()) != null) {
						strBuff.append(result);
					}
					JSONObject json = new JSONObject(strBuff.toString());
					JSONObject subjosn = new JSONObject(json
							.getString("location"));
					getLocalByItude(subjosn.getString("latitude"),
							subjosn.getString("longitude"));

				} catch (Exception e) {
					// TODO: handle exception
					mLocalOkListener.onGetOk("");
				} finally {
					post.abort();
					httpclient = null;
				}

			}
		}).start();
	}

	FileWriter mFileWriter = null;

	// 写文件,保存刚才获取成功的地理位置
	public void saveLocal(String local) {
		// TODO Auto-generated method stub
		try {
			String strFiles = Environment.getExternalStorageDirectory()
					.toString() + "/Local/";
			File outDir = new File(strFiles);
			File outFile = new File(strFiles + "LocalMe.txt");
			if (outDir.exists() == false) {
				outDir.mkdirs();
			}
			System.out.println(outFile.getAbsolutePath());
			if (outFile.exists() == false) {
				System.out.println("outFile.exists()==false");
				outFile.createNewFile();

			}
			System.out.println(outFile.getAbsolutePath());

			mFileWriter = new FileWriter(outFile, true);
			// 加入日期
			Date date = new Date();
			SimpleDateFormat sDataForamat = new SimpleDateFormat(
					"yyyyMMddHHmmss", Locale.CHINA);
			String strTime = sDataForamat.format(date);
			mFileWriter.write(strTime + ":" + local + "\n");
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if (mFileWriter != null) {
				try {
					mFileWriter.close();
				} catch (IOException e2) {
					// TODO: handle exception
				}

			}

		}

	}

	// 设置监听类的引用对象
	public void setOnGetLocalOkListener(OnGetLocalOkListener listener) {
		mLocalOkListener = listener;
	}

	// 监听类接口
	public interface OnGetLocalOkListener {
		void onGetOk(String local);
	}
}
